#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：图灵学习 
@File    ：5.下载进度条.py
@IDE     ：PyCharm 
@Author  ：ChenLiGao
@Date    ：2024-11-19 15:09
'''
import requests
from tqdm import tqdm


# def download_video(url, save_path):
#     response = requests.get(url, stream=True)
#     # 获取视频资源大小
#     total_size = int(response.headers.get('content-length', 0))
#
#     # 初始化下载大小
#     downloaded_size = 0
#
#     # unit: 下载单位（字节）
#     # unit_scale: 自动调整单位
#     # unit_divisor: 单位换算（除数为1024）
#     with open(save_path, 'wb') as file, tqdm(total=total_size, unit='B', unit_scale=True, unit_divisor=1024) as bar:
#         for chunk in response.iter_content(chunk_size=1024):
#             if chunk:
#                 file.write(chunk)
#                 downloaded_size += len(chunk)
#                 bar.update(len(chunk))
#
#     print("下载完成...")



def download_video(url, save_path):
    response = requests.get(url, stream=True)
    # 获取视频资源大小
    total_size = int(response.headers.get('content-length', 0))

    # 初始化下载大小
    downloaded_size = 0

    with open(save_path, 'wb') as file:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                file.write(chunk)
                downloaded_size += len(chunk)
                percent = (downloaded_size / total_size) * 100
                print(f"下载进度：{percent:.2f}%")

    print("下载完成...")


# 调用下载函数
video_url = "https://lf26-music-east.douyinstatic.com/obj/ies-music-hj/7406293171556076347.mp3"
path = "5video.mp3"
download_video(video_url, path)